package aop;

import aop.service.DefaultEchoService;
import aop.service.EchoService;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author jackcfan
 * @date 2021/10/3
 */
public class CglibDynamicProxyTest {
    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();

        // 指定 super class = DefaultEchoService.class
        enhancer.setSuperclass(DefaultEchoService.class);

        // 指定拦截接口
        // enhancer.setInterfaces(new Class[]{EchoService.class});

        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object source, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                System.out.println("source instanceof EchoService ? "+(source instanceof EchoService));
                long startTime = System.currentTimeMillis();
                /**
                 * Source -> CGLIB 子类 DefaultEchoService$$EnhancerByCGLIB$$711ff7c2@a67c67e
                 * 目标类  -> DefaultEchoService
                 * 错误使用: Object result = method.invoke(source, args);
                 * 正确调用: methodProxy.invokeSuper(source, args);
                 * */
                Object result = methodProxy.invokeSuper(source, args);
                long costTime = System.currentTimeMillis() - startTime;
                System.out.println("[CGLIB 字节码提升] echo 方法执行的实现：" + costTime + " ms.");
                return result;
            }
        });

        // 创建代理对象
        EchoService echoService = (EchoService) enhancer.create();
        // 输出执行结果
        System.out.println(echoService.echo("Hello,World"));
    }
}
